var express = require('express');
var router = express.Router();
var https = require("https"); // https 请求
var iconv = require("iconv-lite"); // https 请求

/* GET home page. */
router.get('/', function(req, res, next) {
  // res.render('index', { title: 'Express' });
  res.send('xxxxxxxx')
});

// 测试 跨域
router.post('/test', (req, res) => {
    console.log(1, req.body);
    console.log(2, res.query);
    // res.cookie('user', '1212', {maxAge: 1000*60*60*24*60,httpOnly: true});//用cookie保存用户名60天
    setTimeout(()=>{
        res.send('post 访问成功' + ' id = ' + req.body.id)
    }, 2000)
});

router.get('/test', (req, res) => {
    console.log(3, req.body);
    console.log(4, res.query);
    setTimeout(()=>{
        res.send('get 访问成功' + ' id = ' + req.query.id)
    }, 2000)

    return

    var appid = 'wx940560c236801d07'
    var secret = 'abbc648071e691cb148a5d9fee2804a8'

    var url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+req.body.code+"&grant_type=authorization_code";
    https.get(url, function (res) {

        console.log(2222222222222,res);

        res.json(res)

        var datas = [];
        var size = 0;
        res.on('data', function (data) {
            datas.push(data);
            size += data.length;
            //process.stdout.write(data);
        });
        res.on("end", function () {
            var buff = Buffer.concat(datas, size);
            var result = iconv.decode(buff, "utf8");//转码//var result = buff.toString();//不需要转编码,直接tostring
            console.log(result);
        });
    }).on("error", function (err) {
        // Logger.error(err.stack)
        // callback.apply(null);
    });

});

router.get('/cookie', (req, res) => {
    console.log(req.body)
    res.cookie('user', 'ycc', {maxAge: 1000*60*60*24*60,httpOnly: true});//用cookie保存用户名60天
    res.send('测试跨域获取 cookie')
})

module.exports = router;
